$package('wstuo.orgMge');
$import('wstuo.orgMge.organizationTree');

/**  
 * @author Van  
 * @constructor WSTO
 * @description 机构列表视图函数
 * @date 2011-02-25
 * @since version 1.0 
 * @param {Num} organizationGridOperationFlag 动作标识 
 */
wstuo.orgMge.organizationGrid= function() {
	
	/**
	 * 动作标识.
	 */
	this.organizationGridOperationFlag='';
	
	this.treeType="inner";
		
	return {
		
		/**
		 * @description 格式化
		 * @param cell 当前列值
		 * @param event 事件
		 * @param data 行数据
		 */
		orgGridFormatter:function(cell,opt,data){

			return actionFormat(viewOrglist_edit,viewOrglist_delete)
			.replace('[edit]','wstuo.orgMge.organizationGrid.editOrganizationInLine('+opt.rowId+')')
			.replace('[delete]','wstuo.orgMge.organizationGrid.deleteOrg('+data.orgNo+')');

		},
		
		/**
		 * @description 显示机构列表.
		 */
		showGrid:function(){
			var params = $.extend({},jqGridParams, {
				url:'organization!find.action?companyNo='+companyNo,
				colNames:[i18n['common_id'],i18n['common_name'],i18n['common_phone'],i18n['common_email'],i18n['common_address'],i18n.common_owner,i18n['common_action'],'','','','','','','','',''],
				colModel:[
				          {name:'orgNo',width:60,align:'center'},
						  {name:'orgName',width:100,align:'center'},
						  {name:'officePhone',width:80,align:'center'},
						  {name:'email',width:80,align:'center'},
						  {name:'address',width:80,align:'center'},
						  {name:'personInChargeName',index:'personInCharge',width:100,align:'center'},
						  {name:'act', width:80,align:'center',sortable:false,formatter:function(cell,event,data){
							  return $('#orgGridAction').html().replace(/{orgNo}/g,event.rowId);
						  }},
						  {name:'officeFax',hidden:true},
						  {name:'homePage',hidden:true},
						  {name:'logo',hidden:true},
						  {name:'orgType',hidden:true},
						  {name:'parentNo',hidden:true},
						  {name:'parentOrgName',hidden:true},
						  {name:'personInChargeName',hidden:true},
						  {name:'personInChargeNo',hidden:true},
						  {name:'dataFlag',hidden:true}
						  ],
				jsonReader: $.extend(jqGridJsonReader, {id: "orgNo"}),
				sortname:'orgNo',
				pager:'#orgGridPager'
			});
			$("#orgGrid").jqGrid(params);
			$("#orgGrid").navGrid('#orgGridPager',navGridParams);
			//列表操作项
			$("#t_orgGrid").css(jqGridTopStyles);
			$("#t_orgGrid").append($('#orgGridToolbar').html());
			//自适应宽度
			setGridWidth("#orgGrid",15);
		},
		
		
		/**
		 * @description 打开新增窗口.
		 */
		addOrganizationOpenWindow:function (){
			
			organizationGridOperationFlag="save";
			resetForm("#organizationWindowForm");
			$('#orgWindow_parentOrgName').removeAttr("readonly");
			$('#orgWindow_parentOrgName').removeAttr("disabled")//将input元素设置为disabled
			windows('organizationWindow',{title:i18n['title_org_addOrg'],width: 500});
		},
		
		/**
		 * @description 进行添加操作.
		 */

		saveOrganization:function (){
			var fullName=$('#organizationDto_personInChargeName_gridAdd').val();
			validateUserByFullName(fullName,wstuo.orgMge.organizationGrid.saveOrganizationMethod);			
		},
		/**
		 * 保存机构方法
		 * @param userId 用户编号
		 */
		saveOrganizationMethod:function(userId){
			var orgName=trim($('#orgWindow_orgName').val());
			$('#orgWindow_orgName').val(orgName);
				//$('#organizationDto_personInChargeNo_gridAdd').val(userId);
				var frm = $('#organizationWindow form').serialize();
				var url = 'organization!'+organizationGridOperationFlag+'.action';
				$.post('organization!isCategoryExistdOnEdit.action', frm, function(data){
	                   if (data) {
	                	   msgShow(i18n.err_orgNameIsExisted,'show');
	                   }  else {
	                		$.post(url,frm, function(){
	        					$('#organizationWindow').dialog('close');
	        					var msg=i18n['msg_org_orgAddSuccessful'];
	        					if(organizationGridOperationFlag=='updateOrgWin'){
	        						msg=i18n['msg_org_orgEditSuccessful'];
	        					}
	        					$('#orgGrid').trigger('reloadGrid');
	        					wstuo.orgMge.organizationTree.loadOrganizationTreeView('#orgTreeDIV');//重新载入树结构
	        					loadTreeView('#selectTreeDIV','organization!findAll.action?companyNo='+companyNo,wstuo.orgMge.organizationGrid.selectTreeNode);
	        					$('#orgWindow_orgType').val('inner');
	        					msgShow(msg,'show');
	        				});
	                   }
				});
		},

		/**
		 * @description 打开编辑窗口.
		 */
		editOrganizationOpenWindow:function (){
			resetForm("#editOrgForm_dialog");
			checkBeforeEditGrid("#orgGrid",wstuo.orgMge.organizationGrid.editOrgMethod);
		},
		
		/**
		 * @description 打开编辑窗口.
		 * @param rowId 行编号
		 */
		editOrganizationOpenWindow_aff:function (rowId){
			resetForm("#editOrgForm_dialog");
			var rowData= $("#orgGrid").jqGrid('getRowData',rowId);  // 行数据  
			wstuo.orgMge.organizationGrid.editOrgMethod(rowData);
		},
		
		/**
		 * 行内编辑
		 * @param rowId 行编号
		 */
		editOrganizationInLine:function(rowId){
			
			var rowData=$('#orgGrid').getRowData(rowId);
			wstuo.orgMge.organizationGrid.editOrgMethod(rowData);
		},
		
		/**
		 * @description 编辑机构方法.
		 * @param rowData  行数据
		 */
		editOrgMethod:function(rowData){
			 $('#orgWindow_orgNo').val(rowData.orgNo);
			 $('#orgWindow_orgName').val(rowData.orgName);
			 $('#orgWindow_officeFax').val(rowData.officeFax);
			 $('#orgWindow_officePhone').val(rowData.officePhone);
			 $('#orgWindow_email').val(rowData.email);
			 $('#orgWindow_address').val(rowData.address);

			 $('#orgWindow_parentOrgName').val(rowData.parentOrgName);
			 $('#orgWindow_parentOrgNo').val(rowData.parentOrgNo);
			 
			 $('#organizationDto_personInChargeName_gridAdd').val(rowData.personInChargeName);
			 $('#organizationDto_personInChargeNo_gridAdd').val(rowData.personInChargeNo);

			 if(rowData.parentNo==""){
				 $('#orgWindow_parentOrgNo').val("1");
			 }
			 else{
				 
				 $('#orgWindow_parentOrgNo').val(rowData.parentNo);
			 }
			 
			 if(rowData.orgNo=="1"){
				$('#orgWindow_parentOrgName').val(i18n['msg_org_isTheRoot']);
				$('#orgWindow_parentOrgName').attr("disabled",true);//将input元素设置为disabled
				$("#orgWindow_orgType ").empty();
				$("#orgWindow_orgType").append("<option value='company'>"+i18n['label_org_companyInfo']+"</option>");
			 }else{
				 $("#orgWindow_orgType").empty();
				 $('#orgWindow_parentOrgName').attr("disabled","")//将input元素设置为disabled
				 if(rowData.orgType=="inner"){
					 treeType="inner";
					 $("#orgWindow_orgType").append("<option value='inner'>"+i18n['title_sla_byServiceOrg']+"</option>");
				 }
				 if(rowData.orgType=="services"){
					 treeType="services";
					 $("#orgWindow_orgType").append("<option value='services'>"+i18n['msg_org_serviceOrg']+"</option>");
					 
				 }
			 }
			 organizationGridOperationFlag="updateOrgWin";
			 $('#orgWindow_personInChargeName_choose').click(function(){//选择机构负责人
				wstuo.orgMge.organizationMain.selectPersonIncharge('#organizationDto_personInChargeNo_gridAdd','#organizationDto_personInChargeName_gridAdd');
				
			 });
			 windows('organizationWindow',{title:i18n['title_org_editOrg'],width: 500});
		},

		/**
		 * @description 删除机构.
		 */
		deleteOrgs:function(){
			checkBeforeDeleteGrid("#orgGrid",wstuo.orgMge.organizationGrid.deleteOrgMethod);
		},
		
		/**
		 * @description 删除机构.
		 * @param orgNo  机构编号
		 */
		deleteOrgs_aff:function(orgNo){
			msgConfirm(i18n.msg_msg,i18n['msg_confirmDelete'],function(){
				wstuo.orgMge.organizationGrid.deleteOrgMethod(orgNo);
			});
		},
		
		/**
		 * @description 删除机构Method.
		 * @param  rowIds  机构的编号
		 */
		deleteOrgMethod:function(rowIds){
			var arr = $("#orgGrid").jqGrid("getRowData",rowIds);
			if(arr.dataFlag === "1"){
				msgShow(i18n['msg_canNotDeleteSystemData'],'warning');
				return false;
			}
			var param = $.param({'orgNos':rowIds},true);
			$.post("organization!deleteOrgs.action", param, function(data)
			{
				if(data==null){
					$('#orgGrid').trigger('reloadGrid');
					wstuo.orgMge.organizationTree.loadOrganizationTreeView('#orgTreeDIV');//重新载入树结构
					msgShow(i18n['msg_deleteSuccessful'],'info');
				}else{
					msgShow(i18n['msg_org_deleteErrorKey'],'info');
				}
			}, "json");
		},
		

		/**
		 * @description 删除机构InLineMethod.
		 * @param rowId  行的编号
		 */
		deleteOrg:function(rowId){
						
			confirmBeforeDelete(function(){
				
				var url = "organization!remove.action";
				var params = {"orgNo" :rowId};
				$.post(url,params,function (r) {
						$('#orgGrid').trigger('reloadGrid');
						wstuo.orgMge.organizationTree.loadOrganizationTreeView('#orgTreeDIV');//重新载入树结构
						msgShow(i18n['msg_deleteSuccessful'],'info');
						
				},'json');
			});

		},

		
		/**
		 * @description 搜索机构.
		 */
		searchOrg_openwindow:function(){
			windows('searchOrg_win',{width: 350,modal: false});
		},
		

		/**
		 * @description 搜索机构Method.
		 */
		searchOrg:function(){
			
			var _url = 'organization!find.action?companyNo='+companyNo;	
			searchGridWithForm('#orgGrid','#searchOrg_win',_url);

		},
		
		
		/**
		 * @description 选择树.
		 */
		selectParentOrganization:function(){
			
			windows('selectTree',{width: 250,height: 350});
			loadTreeView('#selectTreeDIV','organization!findAll.action?companyNo='+companyNo,wstuo.orgMge.organizationGrid.selectTreeNode);
			
		},
		
		
		/**
		 * @description 选择节点.
		 * @param  事件
		 * @param  数据
		 */
		selectTreeNode:function(event, data){
			
			var orgNo=data.rslt.obj.attr("orgNo");
			var orgName=data.rslt.obj.attr("orgName");
			$('#orgWindow_parentOrgName').val(orgName).focus();
			$('#orgWindow_parentOrgNo').val(orgNo);
			var orgType=data.rslt.obj.attr("orgType");
			if(orgType.indexOf("inner")>=0||orgType.indexOf("innerPanel")>=0||orgType.indexOf("itsop")>=-0||orgType.indexOf("ROOT")>=0){
				$("#orgWindow_orgType>option[value='inner']").remove();
				$("#orgWindow_orgType>option[value='services']").remove();
				$("<option value='inner'>"+i18n['title_sla_byServiceOrg']+"</option>").appendTo("#orgWindow_orgType");
			}
			
			if(orgType.indexOf("services")>=0||orgType.indexOf("servicesPanel")>=0){
				$("#orgWindow_orgType>option[value='inner']").remove();
				$("#orgWindow_orgType>option[value='services']").remove();
				$("<option value='services'>"+i18n['msg_org_serviceOrg']+"</option>").appendTo("#orgWindow_orgType");
			}
			
			
			if(orgType.indexOf("company")>=0){
				
				$("#orgWindow_orgType>option[value='inner']").remove();
				$("#orgWindow_orgType>option[value='services']").remove();
				
				$("<option value='services'>"+i18n['msg_org_serviceOrg']+"</option>").appendTo("#orgWindow_orgType");
				$("<option value='inner'>"+i18n['title_sla_byServiceOrg']+"</option>").appendTo("#orgWindow_orgType");
			}
			$('#orgWindow_parentOrgName').focus();
			$('#selectTree').dialog('close');
		},
		
		/**
		 * 导出数据.
		 */
		exportOrganization:function(){
			
			var searchData = $('#searchOrg_win form').getForm();
			var gridData = $("#orgGrid").jqGrid("getGridParam", "postData");   
			
			for(i in searchData){    	   	
				
				if(searchData[i]!="" && searchData[i]!=null){
					
					if(i=='organizationQueryDto.orgName')
						$('#exportOrganization_orgName').val(searchData[i]);
					if(i=='organizationQueryDto.officePhone')
						$('#exportOrganization_officePhone').val(searchData[i]);
					if(i=='organizationQueryDto.address')
						$('#exportOrganization_address').val(searchData[i]);
				}
			}

			$('#exportOrganization_sidx').val(gridData.sidx);
			$('#exportOrganization_sord').val(gridData.sord);
			$('#exportOrganization_page').val(gridData.page);
			$('#exportOrganization_rows').val(gridData.rows);
			$('#exportOrganization_companyNo').val(companyNo);

			$('#exportOrganizationForm').submit();
		},
		/**
		 * 导入
		 */
		doImport:function(){
			var path=$('#importFile').val();
			if(path!=""){
				startProcess();
				$.ajaxFileUpload({
		            url:'organization!importOrganization.action',
		            secureuri:false,
		            fileElementId:'importFile', 
		            dataType:'json',
		            success: function(data,status){
						$('#index_import_excel_window').dialog('close');
						$('#orgGrid').trigger('reloadGrid');
						if(data=='failure'){
							msgShow(i18n['msg_dc_importFailure']);
							endProcess();
						}else{
							msgAlert(data.replace('Total',i18n['opertionTotal']).replace('Insert',i18n['newAdd']).replace('Update',i18n['update']).replace('Failure',i18n['failure']));
							endProcess();
						}
		            	resetForm('#index_import_excel_window form');
		            	//重新载入树结构
						wstuo.orgMge.organizationTree.loadOrganizationTreeView('#orgTreeDIV');
		            }
		      });
			}else{
				msgAlert(i18n['msg_dc_fileNull']);
				endProcess();
			}
		},

		/**
		 * 初始化加载
		 */
		init:function(){	
			//加载机构列表
			setTimeout(function(){
				wstuo.orgMge.organizationGrid.showGrid();
				
				$('#organizationExport').click(wstuo.orgMge.organizationGrid.exportOrganization);//导出数据
				
				//导入数据
				$('#organizationImport').click(function(){
					if(language=="en_US"){
						$('#index_import_href').attr('href',"../importFile/en/Organizations.zip");
					}else{
						$('#index_import_href').attr('href',"../importFile/Organizations.zip");
					}
					windows('index_import_excel_window',{width:400});
					$('#index_import_confirm').unbind().click(wstuo.orgMge.organizationGrid.doImport);
				});
				
				//绑定事件			
				$('#organizationGrid_add').click(wstuo.orgMge.organizationGrid.addOrganizationOpenWindow);
				$('#organizationGrid_edit').click(wstuo.orgMge.organizationGrid.editOrganizationOpenWindow);
				$('#organizationGrid_delete').click(wstuo.orgMge.organizationGrid.deleteOrgs);
				$('#organizationGrid_search').click(wstuo.orgMge.organizationGrid.searchOrg_openwindow);
				
				//$("#saveOrganizationBtn").click(wstuo.orgMge.organizationGrid.saveOrganization);
				//搜索机构
				$("#searchOrgBtn_OK").click(wstuo.orgMge.organizationGrid.searchOrg);
				
				//选择父节点
				$('#orgWindow_parentOrgName').click(wstuo.orgMge.organizationGrid.selectParentOrganization);
			},0);
		}
	};
}();


